from scapy.all import *
from datetime import datetime

def parse_ftp_pcap(pcap_file, output_csv):
    packets = rdpcap(pcap_file)
    log_entries = []
    
    for pkt in packets:
        if pkt.haslayer(TCP) and pkt.haslayer(Raw):
            try:
                payload = pkt[Raw].load.decode('utf-8').strip()
                # 提取 USER 命令
                if payload.startswith('USER'):
                    username = payload.split('USER ')[1]
                    entry = {
                        'time': datetime.fromtimestamp(pkt.time).strftime('%Y-%m-%d %H:%M:%S'),
                        'src_mac': pkt[Ether].src,
                        'src_ip': pkt[IP].src,
                        'dst_mac': pkt[Ether].dst,
                        'dst_ip': pkt[IP].dst,
                        'username': username,
                        'password': '',
                        'status': ''
                    }
                    log_entries.append(entry)
                # 提取 PASS 命令
                elif payload.startswith('PASS'):
                    password = payload.split('PASS ')[1]
                    if log_entries:  # 关联最近的 USER 记录
                        log_entries[-1]['password'] = password
                # 检查响应码
                elif '230 Login successful' in payload:
                    log_entries[-1]['status'] = 'SUCCEED'
                elif '530 Login incorrect' in payload:
                    log_entries[-1]['status'] = 'FAILED'
            except:
                continue
    
    # 写入 CSV
    with open(output_csv, 'w') as f:
        f.write("时间,源MAC,源IP,目标MAC,目标IP,登录名,口令,成功与否\n")
        for entry in log_entries:
            f.write(f"{entry['time']},{entry['src_mac']},{entry['src_ip']},"
                    f"{entry['dst_mac']},{entry['dst_ip']},{entry['username']},"
                    f"{entry['password']},{entry['status']}\n")
            
    #运行
parse_ftp_pcap("ftp_capture.pcap", "ftp_log_20250402.csv")